<?php

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
mysql_select_db("player_profile", $con);
function echoResults($result){
	$rows = array();
	while($r = mysql_fetch_assoc($result)){
		$rows[] = $r;
	}
	echo json_encode($rows);
}

$name = $_GET['name'];
$first = $last = "";
$first_initial = "";
if(preg_match("/ /", $name)){
	$parts = explode(" ", $name);
	$first = $parts[0];
	$last = $parts[1];
	preg_match("/[a-zA-Z]{1}/", $first, $matches);
	$first_initial = $matches[0];
}
else{
	$last = $name;
}
$select = sprintf("SELECT * FROM players WHERE first_name ='%s' and last_name='%s'",
            mysql_real_escape_string($first), mysql_real_escape_string($last));
$r1 = mysql_query($select);
if(mysql_num_rows($r1) == 0){
	$select = sprintf("SELECT * FROM players WHERE first_name like '%s' and last_name = '%s' limit 15",
            "%".mysql_real_escape_string($first)."%", mysql_real_escape_string($last)."%");
	$r2 = mysql_query($select);
	if(mysql_num_rows($r2) == 0){
		$select = sprintf("SELECT * FROM players WHERE first_name like '%s' and last_name like '%s' limit 15",
				mysql_real_escape_string($first_initial)."%", mysql_real_escape_string($last)."%");
		$r3 = mysql_query($select);
		if(mysql_num_rows($r3) == 0){
			$select = sprintf("SELECT * FROM players WHERE last_name like '%s' limit 15",
				mysql_real_escape_string($last)."%");
			$r4 = mysql_query($select);
			if(mysql_num_rows($r4) == 0){
				$select = sprintf("SELECT * FROM players WHERE last_name like '%s' limit 15",
					"%".mysql_real_escape_string($last)."%");
				$r5 = mysql_query($select);
				echoResults($r5);
			}else{
				echoResults($r4);
			}
		}else{
			echoResults($r3);
		}
	}
	else{
		echoResults($r2);
	}
}
else{
	echoResults($r1);
}

?>